package com.cuanbo.dualscreenteachfu.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.os.Build;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.cuanbo.dualscreenteachfu.utils.ArrayUtil;
import com.cuanbo.dualscreenteachfu.utils.LogUtil;

import java.util.Date;
import java.util.List;

/**
 * 自动更新服务
 */
public class AutoUpdateService extends AccessibilityService {
    public static AutoUpdateService mService;
    public static long recordTime = 0;
    public static boolean checkANR=false;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        mService = this;
        LogUtil.add("检查", "服务开始连接", "自动化");
        recordTime = new Date().getTime();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if(checkANR){
            checkANR=false;
            clickByText("关闭应用");
        }
        long nowTime = new Date().getTime();
        long diff = nowTime - recordTime;
        if (diff > 1000 * 20) return;
        clickByText("继续", "android.widget.Button", "android:id/button1");
        clickByText("安装", "android.widget.Button", "android:id/button1");
        clickByText("安装", "android.widget.Button", "com.android.packageinstaller:id/ok_button");
        clickByText("打开", "android.widget.Button", "android:id/button1");
        clickByText("打开", "android.widget.Button", "com.android.packageinstaller:id/launch_button");
        clickByText("安装", "android.widget.Button", "com.android.packageinstaller:id/ok_button");
        clickByText("启用此设备管理应用");
        clickByText("激活此设备管理员");
        clickByText("允许", "android.widget.Button", "com.android.packageinstaller:id/permission_allow_button");
        clickByText("允许", "android.widget.Button", "com.android.permissioncontroller:id/permission_allow_button");
        clickByText("设置", "android.widget.Button", "android:id/button1");
        if (clickByText("允许显示在其他应用的上层")) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            performGlobalAction(GLOBAL_ACTION_BACK);
        }
        if (clickByText("允许出现在其他应用上")) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            performGlobalAction(GLOBAL_ACTION_BACK);
        }
        if (clickByText("允许来自此来源的应用")) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            performGlobalAction(GLOBAL_ACTION_BACK);
        }
    }

    private boolean clickByText(String text) {
        return clickByText(text, null, null);
    }

    private boolean clickByText(String text, String buttonType) {
        return clickByText(text, buttonType, null);
    }

    private boolean clickByText(String text, String buttonType, String viewIdResourceName) {
        boolean result = false;
        AccessibilityNodeInfo rootInfo = getRootInActiveWindow();
        if (rootInfo == null) return false;
        List<AccessibilityNodeInfo> list = rootInfo.findAccessibilityNodeInfosByText(text);
        if (ArrayUtil.isEmptyArray(list)) return false;
        for (AccessibilityNodeInfo info : list) {
            try {
                if (viewIdResourceName == null && buttonType == null) {
                    if (info.getText() != null && info.getText().toString().equals(text)) {
                        String strLog = "文本内容=" + text + " 类名=" + info.getClassName() + " 描述=" + info.getContentDescription() + "资源名称=" + info.getViewIdResourceName();
                        LogUtil.add("点击", strLog, "自动化");
                        dispatchGestureClick(info);
                        if (text.equals("打开")) {
                            recordTime = 0;
                        }
                        result = true;
                    }
                } else if (viewIdResourceName == null) {
                    if (info.getText() != null && info.getText().toString().equals(text) && viewIdResourceName.equals(info.getViewIdResourceName())) {
                        String strLog = "文本内容=" + text + " 类名=" + info.getClassName() + " 描述=" + info.getContentDescription() + "资源名称=" + info.getViewIdResourceName();
                        LogUtil.add("点击", strLog, "自动化");
                        dispatchGestureClick(info);
                        if (text.equals("打开")) {
                            recordTime = 0;
                        }
                        result = true;
                    }
                } else if (buttonType == null) {
                    if (info.getText() != null && info.getText().toString().equals(text) && info.getClassName().equals(buttonType)) {
                        String strLog = "文本内容=" + text + " 类名=" + info.getClassName() + " 描述=" + info.getContentDescription() + "资源名称=" + info.getViewIdResourceName();
                        LogUtil.add("点击", strLog, "自动化");
                        dispatchGestureClick(info);
                        result = true;
                    }
                } else {
                    if (info.getText() != null && info.getText().toString().equals(text) && info.getClassName().equals(buttonType) && viewIdResourceName.equals(info.getViewIdResourceName())) {
                        String strLog = "文本内容=" + text + " 类名=" + info.getClassName() + " 描述=" + info.getContentDescription() + "资源名称=" + info.getViewIdResourceName();
                        LogUtil.add("点击", strLog, "自动化");
                        dispatchGestureClick(info);
                        if (text.equals("打开")) {
                            recordTime = 0;
                        }
                        result = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            info.recycle();
        }
        return result;
    }

    @Override
    public void onInterrupt() {

    }

    /**
     * 点击指定位置
     * 注意7.0以上的手机才有此方法，请确保运行在7.0手机上
     */
    public void dispatchGestureClick(int x, int y) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            LogUtil.add("错误", "当前安卓系统版本低于7.0,无法调用dispatchGesture()该方法!", "自动化");
            return;
        }
        Path path = new Path();
        path.moveTo(x - 1, y - 1);
        path.lineTo(x + 1, y + 1);
        dispatchGesture(new GestureDescription.Builder().addStroke(new GestureDescription.StrokeDescription
                (path, 0, 100)).build(), null, null);
    }

    /**
     * 有些应用和谐了该方法
     */
    public void dispatchGestureClick(AccessibilityNodeInfo info) {
        info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        /*Rect rect = new Rect();
        info.getBoundsInScreen(rect);
        dispatchGestureClick(rect.centerX(), rect.centerY());*/
    }

    /**
     * 由于太多,最好回收这些AccessibilityNodeInfo
     */
    public static void recycleAccessibilityNodeInfo(List<AccessibilityNodeInfo> listInfo) {
        if (ArrayUtil.isEmptyArray(listInfo)) return;

        for (AccessibilityNodeInfo info : listInfo) {
            info.recycle();
        }
    }
}
